package main

import (
	"cogpt/internal/log"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

// CORSMiddleware is the middleware for CORS.
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Allow-Methods", "*")
		c.Header("Access-Control-Allow-Headers", "*")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
			return
		}

		c.Next()
	}
}

// LoggerMiddleware is the middleware for logging.
func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery
		requestHeader := c.Request.Header

		c.Next()

		latency := time.Since(start)
		log.Logger.Debug().
			Str("type", "request").
			Str("Query", raw).
			Str("Request Header", fmt.Sprintf("%v", requestHeader)).
			Str("Response Header", fmt.Sprintf("%v", c.Writer.Header())).
			Msg("")
		log.Logger.Info().
			Msgf("Request completed: | %3d | %13v | %15s | %-7s %s", c.Writer.Status(), latency, c.ClientIP(), c.Request.Method, path)
	}
}
